/**
 * Copyright (c) 2005-2012 springside.org.cn
 */
package com.springBoot.springBootSysCore.common.utils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;

import com.springBoot.springBootSysCore.common.utils.json.JsonDateValueProcessor;
import com.springBoot.springBootSysCore.common.utils.reflection.ReflectionUtils;
import com.springBoot.springBootSysCore.common.utils.reflection.Reflections;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

/**
 * Collections工具集.
 * 在JDK的Collections和Guava的Collections2后, 命名为Collections3.
 * @author calvin
 * @version 2013-01-15
 */
@SuppressWarnings("rawtypes")
public class Collections3 {

	/**
	 * 提取集合中的对象的两个属性(通过Getter函数), 组合成Map.
	 * 
	 * @param collection 来源集合.
	 * @param keyPropertyName 要提取为Map中的Key值的属性名.
	 * @param valuePropertyName 要提取为Map中的Value值的属性名.
	 */
	@SuppressWarnings("unchecked")
	public static Map extractToMap(final Collection collection, final String keyPropertyName,final String valuePropertyName) {
		Map map = new HashMap(collection.size());

		try {
			for (Object obj : collection) {
				map.put(PropertyUtils.getProperty(obj, keyPropertyName),
						PropertyUtils.getProperty(obj, valuePropertyName));
			}
		} catch (Exception e) {
			throw Reflections.convertReflectionExceptionToUnchecked(e);
		}

		return map;
	}

	/**
	 * 提取集合中的对象的一个属性(通过Getter函数), 组合成List.
	 * 
	 * @param collection 来源集合.
	 * @param propertyName 要提取的属性名.
	 */
	@SuppressWarnings("unchecked")
	public static List extractToList(final Collection collection, final String propertyName) {
		List list = new ArrayList(collection.size());

		try {
			for (Object obj : collection) {
				list.add(PropertyUtils.getProperty(obj, propertyName));
			}
		} catch (Exception e) {
			throw Reflections.convertReflectionExceptionToUnchecked(e);
		}

		return list;
	}

	/**
	 * 提取集合中的对象的一个属性(通过Getter函数), 组合成由分割符分隔的字符串.
	 * 
	 * @param collection 来源集合.
	 * @param propertyName 要提取的属性名.
	 * @param separator 分隔符.
	 */
	public static String extractToString(final Collection collection, final String propertyName, final String separator) {
		List list = extractToList(collection, propertyName);
		return StringUtils.join(list, separator);
	}

	/**
	 * 转换Collection所有元素(通过toString())为String, 中间以 separator分隔。
	 */
	public static String convertToString(final Collection collection, final String separator) {
		return StringUtils.join(collection, separator);
	}

	/**
	 * 转换Collection所有元素(通过toString())为String, 每个元素的前面加入prefix，后面加入postfix，如<div>mymessage</div>。
	 */
	public static String convertToString(final Collection collection, final String prefix, final String postfix) {
		StringBuilder builder = new StringBuilder();
		for (Object o : collection) {
			builder.append(prefix).append(o).append(postfix);
		}
		return builder.toString();
	}

	/**
	 * 判断是否为空.
	 */
	public static boolean isEmpty(Collection collection) {
		return (collection == null || collection.isEmpty());
	}

	/**
	 * 取得Collection的第一个元素，如果collection为空返回null.
	 */
	public static <T> T getFirst(Collection<T> collection) {
		if (isEmpty(collection)) {
			return null;
		}

		return collection.iterator().next();
	}

	/**
	 * 获取Collection的最后一个元素 ，如果collection为空返回null.
	 */
	public static <T> T getLast(Collection<T> collection) {
		if (isEmpty(collection)) {
			return null;
		}

		//当类型为List时，直接取得最后一个元素 。
		if (collection instanceof List) {
			List<T> list = (List<T>) collection;
			return list.get(list.size() - 1);
		}

		//其他类型通过iterator滚动到最后一个元素.
		Iterator<T> iterator = collection.iterator();
		while (true) {
			T current = iterator.next();
			if (!iterator.hasNext()) {
				return current;
			}
		}
	}

	/**
	 * 返回a+b的新List.
	 */
	public static <T> List<T> union(final Collection<T> a, final Collection<T> b) {
		List<T> result = new ArrayList<T>(a);
		result.addAll(b);
		return result;
	}

	/**
	 * 返回a-b的新List.
	 */
	public static <T> List<T> subtract(final Collection<T> a, final Collection<T> b) {
		List<T> list = new ArrayList<T>(a);
		for (T element : b) {
			list.remove(element);
		}

		return list;
	}

	/**
	 * 返回a与b的交集的新List.
	 */
	public static <T> List<T> intersection(Collection<T> a, Collection<T> b) {
		List<T> list = new ArrayList<T>();

		for (T element : a) {
			if (b.contains(element)) {
				list.add(element);
			}
		}
		return list;
	}
	
	/**
	 * 去除指定的元素[字符串]
	 * @param source	准备被去除的数据
	 * @param filter	想要去的数据
	 */
	public static String wipeOffFilterString(String source,String filter){
		Object[] result = wipeOffFilter(source != null?source.split(","):new String[]{}, 
				filter != null?filter.split(","):new String[]{});
		return StringUtils.join(result,",");
	}
	
	/**
	 * 去除指定的元素[数组]
	 * @param source	准备被去除的数据
	 * @param filter	想要去的数据
	 */
	public static Object[] wipeOffFilter(Object[] source,Object[] filter){
		List<Object> sourceList = new ArrayList<Object>(Arrays.asList(source));
		List<Object> filterList = new ArrayList<Object>(Arrays.asList(filter));
		
		Iterator<Object> it =  sourceList.iterator();
		while(it.hasNext()){
			Object obj = it.next();
			if(filterList.contains(obj) || StringUtils.isEmpty(obj.toString().trim())){
				it.remove();
			}
		}
		
		return sourceList.toArray();
	}
	

	/**
	 * 返回JSON对象
	 * @param object	需要转换的对象
	 * @param excludes	需忽略字段
	 * @return
	 */
	public static Object returnJsonObj(Object object,String[] excludes){
		JSONObject jsonObj = null;
		
		JsonConfig jsonConfig = new JsonConfig();  //建立配置文件
		jsonConfig.setIgnoreDefaultExcludes(false);  //设置默认忽略
		if(excludes != null && excludes.length >= 1){
			jsonConfig.setExcludes(excludes);//将所需忽略字段加到数组中
		}
		jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor("yyyy-MM-dd HH:mm:ss")); 
		jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class, new JsonDateValueProcessor("yyyy-MM-dd HH:mm:ss"));  
		
		jsonObj = JSONObject.fromObject(object,jsonConfig);
		
		System.err.println("返回格式："+jsonObj.toString());
		return jsonObj;
	}
	
	/**
	 * list数组转json数组 只取其中某些字段 并可以做替换
	 * @param object  要转换的list对象数组
	 * @param className 对象的class
	 * @param lable 对象中要取的值
	 * @param value 要替换成为的值 如 lable['id','name']  value['id','text'] 可以为null
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	@SuppressWarnings({ "static-access" })
	public static <T> JSONArray listToJsonArraySelect(List<T> object, Class<? extends Object> className,String lable[],String value[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		StringBuffer sb=new StringBuffer();
		sb.append("[");
		List<Field> fields = new ArrayList<Field>();
		for(String k : lable){
			fields.add(ReflectionUtils.getDeclaredField(className.newInstance(), k));
		}
        for (int j = 0; j < object.size(); j++) {
        	for(int i = 0;i<fields.size();i++){
        		if(i==0){
        			sb.append("{ ");
        		}else{
        			sb.append(",");
        		}
        		Object v = value==null?lable[i]:value[i];
        		if(fields.get(i)!=null){
        			fields.get(i).setAccessible(true) ;
            		sb.append(v+": '"+fields.get(i).get(object.get(j))+"'");
            	}else{
            		sb.append(v+": ''");
            	}	
        		if(i==fields.size()-1){
        			sb.append("},");
        		}
        	}
            try {
            	
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
		sb.deleteCharAt(sb.length() - 1);
		sb.append("]");
		String stringJson = sb.toString();
		JSONArray json=new JSONArray();
		JSONArray fromObject=null;
		if(object != null && object.size()>0) {
			fromObject = json.fromObject(stringJson);
		}
		return fromObject;
	}
	/**
	 * list数组转json字符串 只取其中某些字段 并可以做替换
	 * @param object  要转换的list对象数组
	 * @param className 对象的class
	 * @param lable 对象中要取的值
	 * @param value 要替换成为的值 如 lable['id','name']  value['id','text'] 可以为null
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	public static <T> String listToJsonStringSelect(List<T> object, Class<? extends Object> className,String lable[],String value[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		StringBuffer sb=new StringBuffer();
		sb.append("[");
		List<Field> fields = new ArrayList<Field>();
		for(String k : lable){
			fields.add(ReflectionUtils.getDeclaredField(className.newInstance(), k));
		}
        for (int j = 0; j < object.size(); j++) {
        	for(int i = 0;i<fields.size();i++){
        		if(i==0){
        			sb.append("{ ");
        		}else{
        			sb.append(",");
        		}
        		Object v = value==null?lable[i]:value[i];
        		if(fields.get(i)!=null){
        			fields.get(i).setAccessible(true) ;
            		sb.append(v+": '"+fields.get(i).get(object.get(j))+"'");
            	}else{
            		sb.append(v+": ''");
            	}	
        		if(i==fields.size()-1){
        			sb.append("},");
        		}
        	}
            try {
            	
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
		sb.deleteCharAt(sb.length() - 1);
		sb.append("]");
		return sb.toString();
	}
	
	/**
	 * 获取不重复的集合  （根据指定的对象属性判断重复对象）
	 * yh
	 * 2017年10月11日
	 * @param object
	 * @param className
	 * @param properties
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	@SuppressWarnings("unchecked")
	public static <T> List<T>  getNoRepetitionCollectionToProperties(List<T> object,String className,String properties) throws InstantiationException, IllegalAccessException, ClassNotFoundException{
		Object ot = Class.forName(className).newInstance();
		Class<? extends Object> c = ot.getClass();
		Field[] fields = c.getDeclaredFields();//取得所有类成员变量
		//遍历所有类成员变量，判断是否有传入的属性 
	    for (Field f:fields) {
	    	//取消每个属性的安全检查
	    	 f.setAccessible(true);
	    }
	    Map<String,T> map = new HashMap<String, T>();
	    //打印传入的每个对象的所有类成员属性值
        for (int j = 0; j < object.size(); j++) {
            for (int i = 0; i < fields.length; i++) {
                try {
                    //System.out.println(fields[i].getName() + ":" + fields[i].get(object.get(j)));
                    if(properties.equals(fields[i].getName()) ) {//存在传入的属性
                    	map.put(fields[i].get(object.get(j)).toString(),object.get(j));
       	    	 	}
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        object.clear();
		for(Object code : map.values()) {
			object.add((T)code);
		}
		return object;
		
	}

}
